package com.example.utils.download;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 用于导出客户信息的工具类
 * @Author runto
 * @Date 2023/10/13 22:21
 * @PackageName:com.example.utils.download
 * @ClassName: DownloadExcelUtil
 * @Version 1.0
 */
public class DownloadExcelUtil {

    private static final String EXCEL_XLS = "xls";
    private static final String EXCEL_XLSX = "xlsx";
    public static final String YYYYMMDDHHMISS="yyyyMMddHHmmss";


    public static boolean deleteFile(String filePath){
        boolean flag=false;
        File file=new File(filePath);
        if(file.exists()){
            file.delete();
            flag=true;
        }
        return flag;
    }

    /**
     * 生成一个新的文件
     * @param path
     * @param fileName
     * @return
     * @throws Exception
     */
    public static String makerNewExcel(String path,String fileName)throws Exception{
        String newPath=null;
        File file=new File(path+File.separator+fileName);
        if(file.exists()){
            String newName=fileName.split("\\.")[0]+System.currentTimeMillis()+"."+fileName.split("\\.")[1];
            newPath=path+File.separator+newName;
            File dexFile=new File(newPath);
            FileUtils.copyFile(file,dexFile);
        }
        return newPath;
    }
    /**
     *
     * @Description 按照pattern格式获取其他时间点
     * @author caiyt
     */
    public static String getDateFormat(Date date, String pattern) {
        DateFormat format = new SimpleDateFormat(pattern);
        return format.format(date);
    }



    public static void writeExcel(List<List<String>> list, String finalXlsxPath){
        OutputStream out = null;
        try {
            // 读取Excel文档
            File finalXlsxFile = new File(finalXlsxPath);
            Workbook workBook = getWorkbok(finalXlsxFile);
            // sheet 对应一个工作页
            Sheet sheet = workBook.getSheetAt(0);
            //设置导出样式
            CellStyle cellStyle = workBook.createCellStyle();
            Font font = workBook.createFont();
            font.setFontName("微软雅黑");
            font.setFontHeightInPoints((short) 10);// 字体大小
            cellStyle.setFont(font);
            cellStyle.setWrapText(true);//自动换行
            cellStyle.setBorderBottom(BorderStyle.THIN); // 下边框
            cellStyle.setBorderLeft(BorderStyle.THIN);// 左边框
            cellStyle.setBorderTop(BorderStyle.THIN);// 上边框
            cellStyle.setBorderRight(BorderStyle.THIN);// 右边框
            cellStyle.setAlignment(HorizontalAlignment.CENTER);// 左右居中
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中

            // 创建文件输出流，输出电子表格：这个必须有，否则你在sheet上做的任何操作都不会有效

            /**
             * 往Excel中写新数据
             */
            for (int j = 0; j < list.size(); j++) {
                // 创建一行：从第二行开始，跳过属性列
                Row row = sheet.createRow(j+1);
                // 得到要插入的每一条记录
                List<String> listStr=list.get(j);
                for (int k = 0; k <listStr.size(); k++) {
                    Cell first = row.createCell(k);
                    first.setCellStyle(cellStyle);
                    first.setCellValue(listStr.get(k));
                }
            }
            // 创建文件输出流，准备输出电子表格：这个必须有，否则你在sheet上做的任何操作都不会有效
            out =  new FileOutputStream(finalXlsxPath);
            workBook.write(out);
        } catch (Exception e) {

        } finally{
            try {
                if(out != null){
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {

            }
        }
    }

    /**
     * 判断Excel的版本,获取Workbook
     * @return
     * @throws IOException
     */
    public static Workbook getWorkbok(File file) throws IOException{
        Workbook wb = null;
        FileInputStream in = new FileInputStream(file);
        if(file.getName().endsWith(EXCEL_XLS)){	 //Excel 2003
            wb = new HSSFWorkbook(in);
        }else if(file.getName().endsWith(EXCEL_XLSX)){	// Excel 2007/2010
            wb = new XSSFWorkbook(in);
        }
        return wb;
    }




    /**
     * 文件处理   第N列有缺失数据
     */
    public static final String LACK_TEMPLET = "0200013";
    /**
     * 文件处理   第N列有多余数据
     */
    public static final String SURPLUS_TEMPLET = "0200014";
    /**
     * 文件处理   第N列有重复数据
     */
    public static final String REPEAT_TEMPLET = "0200012";
    /**
     * 文件处理   文件格式错误或无数据
     */
    public static final String FORM_TEMPLET = "0200011";
    // 业务成功代码
    public static final String BUSI_SUCCESS_CODE = "000000";
    // 业务成功代码对应的信息
    public static final String BUSI_SUCCESS_MESSAGE = "操作成功";
    // 业务失败默认代码
    public static final String BUSI_FAILURE_CODE = "999999";
    // 业务失败默认代码对应的信息
    public static final String BUSI_FAILURE_MESSAGE = "操作失败";


    //    private static String[] strs={"enterpriseName","shortEnterpriseName","custIndustry","custIndustryName","email",
//            "sicIndustry","sicIndustryName","customerType","customerTypeName","taxNum","upEnterpriseId","upEnterpriseName",
//            "webSite","customerStatus","customerStatusName","commAddr","remarks"};
    @SuppressWarnings("unused")
    private static final Logger log = LoggerFactory.getLogger(DownloadExcelUtil.class);



    public static List<Map<Integer,Object>> readExcelBody(InputStream inputStream, String suffix, Integer startRow, Integer endCol){
        List<Map<Integer,Object>> list = new ArrayList<Map<Integer,Object>>();
        try {
            Workbook wb;
            if ("xlsx".equalsIgnoreCase(suffix)) {
                wb = new XSSFWorkbook(inputStream);
            }else if("xls".equalsIgnoreCase(suffix)){
                wb = new HSSFWorkbook(inputStream);
            }else{
                wb = null;
            }

            //获得第一个sheet
            Sheet sheet = wb.getSheetAt(0);
            //获得最后一行的行标，比行数小1（得到总行数）
            int rowNum = sheet.getLastRowNum();
            //获得第一行
            Row row = null;
            //获得内容  从第二行开始
            for (int i = startRow; i <= rowNum; i++) {
                row = sheet.getRow(i);
                Map<Integer,Object> map = new HashMap<Integer,Object>();
                for (int j = 0; j < endCol; j++) {
                    //获得每列值
                    XSSFCell cell = (XSSFCell) row.getCell(j);
                    String col ;
                    if(cell==null){
                        col=null;
                    }else{
                        col=getStringVal(cell);
                    }
                    map.put(j, col);
                }
                list.add(map);
            }
        } catch (IOException e) {

        }
        return list;
    }
    public static <T> Object parseValueWithType(String value, Class<?> type) {
        Object result = null;
        try { // 根据属性的类型将内容转换成对应的类型
            if (type.toString().endsWith("java.lang.Boolean")) {
                result = Boolean.parseBoolean(value);
            } else if(type.toString().endsWith("java.lang.Byte")) {
                result = Byte.parseByte(value);
            } else if (type.toString().endsWith("java.lang.Short")) {
                result = Short.parseShort(value);
            } else if (type.toString().endsWith("java.lang.Integer")) {
                result = Integer.parseInt(value);
            } else if (type.toString().endsWith("java.lang.Long")) {
                result = Long.parseLong(value);
            } else if (type.toString().endsWith("java.lang.Float")) {
                result = Float.parseFloat(value);
            } else if (type.toString().endsWith("java.lang.Double")) {
                result = Double.parseDouble(value);
            } else {
                result = (Object) value;
            }
        } catch (Exception e) {

            // 把异常吞掉直接返回null
        }
        return result;
    }

    @SuppressWarnings("deprecation")
    public static String getStringVal(HSSFCell cell){
        switch(cell.getCellType()){
            case BOOLEAN:
                return cell.getBooleanCellValue()?"TRUE":"FALSE";
            case FORMULA:
                return cell.getCellFormula();
            case NUMERIC:
                cell.setCellType(CellType.STRING);
                return cell.getStringCellValue();
            case STRING:
                return cell.getStringCellValue();
            default:
                return "";
        }
    }

    @SuppressWarnings("deprecation")
    public static String getStringVal(XSSFCell cell){
        switch(cell.getCellType()){
            case BOOLEAN:
                return cell.getBooleanCellValue()?"TRUE":"FALSE";
            case FORMULA:
                return cell.getCellFormula();
            case NUMERIC:
                cell.setCellType(CellType.STRING);
                return cell.getStringCellValue();
            case STRING:
                return cell.getStringCellValue();
            default:
                return "";
        }
    }
}
